package com.zwr.normal.sharemodel;

import java.util.concurrent.atomic.AtomicInteger;

public class AccountNoLock implements Account{
    private AtomicInteger balance;

    public AccountNoLock(Integer balance) {
        this.balance = new AtomicInteger(balance);
    }

    @Override
    public  Integer getBalance() {
        return balance.get();
    }

    @Override
    public  void withdraw(Integer amount) {
        while (true){
            int prev = balance.get();
            int nex = prev - amount;
            if(balance.compareAndSet(prev,nex)){
                break;
            }
        }
        // 可以简化下面的方法
//        balance.addAndGet(-1 * amount);

    }

    public static void main(String[] args) {
        Account.demo(new AccountUnsafe(10000));
    }
}
